package com.wcfsy.wechat.wx.controller;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.codehaus.jackson.map.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.wcfsy.wechat.wx.entity.OnlineMenu;
import com.wcfsy.wechat.wx.entity.WechatMenu;
import com.wcfsy.wechat.wx.entity.WechatMenuUtil;
import com.wcfsy.wechat.wx.exception.ServiceException;
import com.wcfsy.wechat.wx.sys.dao.WechatConfigDao;
import com.wcfsy.wechat.wx.sys.dao.WechatMenuDao;
import com.wcfsy.wechat.wx.um.entity.TreeNodeVo;
import com.wcfsy.wechat.wx.util.Constant;
import com.wcfsy.wechat.wx.util.HttpClientUtil;
import com.wcfsy.wechat.wx.util.HttpUtil;
import com.wcfsy.wechat.wx.util.JsonMessage;

@Controller
@RequestMapping("/cms/wechatmenu/")
public class WechatMenuTreeController {
	Logger logger = LoggerFactory.getLogger(this.getClass());
	@Resource
	private WechatConfigDao wechatConfigDao;
	@Resource
	private WechatMenuDao wechatMenuDao;

	@RequestMapping({ "sysnToOnline" })
	@ResponseBody
	public JsonMessage sysnToOnline() throws Exception {
		List<OnlineMenu> menus = wechatMenuDao.findOnlineMenuByRoot();
		for (OnlineMenu menu : menus) {
			List<OnlineMenu> subList = wechatMenuDao
					.findOnlineMenuByParentId(menu.getId());
			logger.info("id={},name={}", menu.getId(), menu.getName());
			if (subList != null && subList.size() > 0) {
				menu.setSub_button(subList);
			}
		}
		Map<String, List<OnlineMenu>> map = new HashMap<String, List<OnlineMenu>>();
		map.put("button", menus);
		ObjectMapper mapper = new ObjectMapper();
		String json = mapper.writeValueAsString(map);
		logger.info("提交json到微信平台 {}", json);
		return WechatMenuUtil.submitWechatMenuJson(wechatConfigDao
				.getWechatToken().getAccess_token(), json);
	}

	@RequestMapping({ "view/page" })
	public ModelAndView mainPage() {
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.setViewName("menu/menutree_manager");
		List<WechatMenu> menus = wechatMenuDao.findByParam(null);
		List<TreeNodeVo> menuTreeNodeList = new ArrayList<TreeNodeVo>(
				menus == null ? 0 : menus.size());
		TreeNodeVo menuTreeNodeVo = null;
		if ((menus != null) && (!menus.isEmpty())) {
			for (WechatMenu menu : menus) {
				menuTreeNodeVo = new TreeNodeVo();
				menuTreeNodeVo.setId(menu.getId() + "");
				menuTreeNodeVo.setParentId(menu.getParentId() + "");
				menuTreeNodeVo.setName(menu.getText());
				menuTreeNodeList.add(menuTreeNodeVo);
			}
		}
		modelAndView.addObject("menuTreeNodeList", menuTreeNodeList);
		try {
			modelAndView.addObject("canDrag", Boolean.valueOf(false));
		} catch (Exception e) {
			modelAndView.addObject("canDrag", Boolean.valueOf(false));
			logger.error("菜单树拖拽控制异常，将导致有修改权限的用户无法拖拽菜单：" + e.getMessage());
		}
		return modelAndView;
	}

	@RequestMapping({ "sysnToDatabase" })
	@ResponseBody
	public JsonMessage sysnToDatabase() throws Exception {
		String access_token = wechatConfigDao.getWechatToken()
				.getAccess_token();
		String result = HttpClientUtil.get(Constant.WX_CREATE_MENU
				+ access_token);
		JSONObject jsonObject = JSON.parseObject(result);
		if (jsonObject.containsKey("errcode")) {
			return JsonMessage.getErrorJson("同步微信菜单失败,errmsg="
					+ jsonObject.getString("errmsg"));
		}
		logger.info("微信公众号菜单:{}", result);
		JSONArray jsonArray = jsonObject.getJSONObject("menu").getJSONArray(
				"button");
		wechatMenuDao.clear();
		for (int i = 0; i < jsonArray.size(); i++) {
			jsonObject = jsonArray.getJSONObject(i);
			WechatMenu menu = WechatMenuUtil.getWechatMenu(jsonObject);
			menu.setParentId(null);
			wechatMenuDao.add(menu);
			this.logger.info("插入数据返回id={}", menu.getId());
			if (jsonObject.containsKey("sub_button")) {
				JSONArray subjsonArray = jsonObject.getJSONArray("sub_button");
				for (int j = 0; subjsonArray != null && j < subjsonArray.size(); j++) {
					jsonObject = subjsonArray.getJSONObject(j);
					WechatMenu subMenu = WechatMenuUtil
							.getWechatMenu(jsonObject);
					subMenu.setParentId(menu.getId());
					wechatMenuDao.add(subMenu);
				}
			}
		}
		return JsonMessage.getSuccessJson("同步成功");
	}

	@RequestMapping("add")
	@ResponseBody
	public ModelAndView addMenu(@Param("id") String id,
			@Param("name") String name) {
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.setViewName("menu/menutree_manager_add");
		modelAndView.addObject("parentId", id);
		try {
			modelAndView.addObject("parentName",
					URLDecoder.decode(name, "UTF-8"));
		} catch (UnsupportedEncodingException e) {
			logger.debug(name + "新增菜单转码异常:" + e.getMessage());
		}
		return modelAndView;
	}

	@RequestMapping("modify")
	@ResponseBody
	public ModelAndView modifyMenu(@Param("id") long id,
			@Param("parentMenuName") String parentMenuName) {
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.setViewName("menu/menutree_manager_modify");
		try {
			modelAndView.addObject("parentName",
					URLDecoder.decode(parentMenuName, "UTF-8"));
		} catch (UnsupportedEncodingException e) {
			logger.error("修改菜单编码转化异常：" + e.getMessage());
		}
		WechatMenu menu = wechatMenuDao.getById(id);
		if (menu != null) {
			modelAndView.addObject("menu", menu);
		}
		return modelAndView;
	}

	@RequestMapping("modify/submit")
	@ResponseBody
	public JsonMessage modifyMenuSubmit(long id, Long parentId, String text,
			String url, int showIndex, String type) {
		JsonMessage jsonMessage = new JsonMessage();
		WechatMenu queryMenu = this.wechatMenuDao.getById(id);
		if (queryMenu == null) {
			throw new ServiceException("MEU001", "数据不存在");
		}

		WechatMenu menu = new WechatMenu();
		try {
			menu.setId(id);
			menu.setParentId(parentId);
			menu.setText(text);
			if (StringUtils.isNotBlank(url)) {
				menu.setUrl(url.trim());
			}
			if (StringUtils.isNotBlank(type)) {
				menu.setType(type);
			}
			menu.setShowIndex(showIndex);
			this.wechatMenuDao.update(menu);
		} catch (ServiceException e) {
			logger.error("更新菜单失败, Menu:" + menu + " 异常：" + e.getCode() + " "
					+ e.getMsg());
			jsonMessage.setSuccess("error");
			jsonMessage.setMessage("更新菜单失败:" + e.getMsg());
			return jsonMessage;
		} catch (Exception e) {
			logger.error("更新菜单失败, Menu:" + menu + " 异常：" + e.getMessage());
			jsonMessage.setSuccess("error");
			jsonMessage.setMessage("更新菜单失败:系统异常");
			return jsonMessage;
		}
		jsonMessage.setSuccess("succeed");
		jsonMessage.setMessage("更新菜单成功");
		jsonMessage.setData(menu);
		return jsonMessage;
	}

	@RequestMapping({ "add/submit" })
	@ResponseBody
	public JsonMessage addMenuSubmit(WechatMenu menu) {
		JsonMessage jsonMessage = new JsonMessage();
		if (menu == null) {
			jsonMessage.setSuccess("error");
			jsonMessage.setMessage("新增菜单失败,传入的参数为空");
			return jsonMessage;
		}
		try {
			if (menu.getParentId() != 0L) {
				WechatMenu parentMenu = this.wechatMenuDao.getById(menu
						.getParentId());
				if (parentMenu == null) {
					throw new ServiceException("MEU002", "父菜单不存在");
				}
			}
			if (StringUtils.isNotBlank(menu.getUrl())) {
				menu.setUrl(menu.getUrl().trim());
			}
			if (StringUtils.isNotBlank(menu.getType())) {
				menu.setType(menu.getType());
			}
			this.wechatMenuDao.add(menu);
		} catch (ServiceException e) {
			logger.error("新增菜单失败:" + menu + " 异常：" + e.getCode() + " "
					+ e.getMsg());
			jsonMessage.setSuccess("error");
			jsonMessage.setMessage("新增菜单失败:" + e.getMsg());
			return jsonMessage;
		} catch (Exception e) {
			logger.error("新增菜单失败:" + menu + " 异常：" + e.getMessage());
			jsonMessage.setSuccess("error");
			jsonMessage.setMessage("新增菜单失败:系统异常");
			return jsonMessage;
		}
		jsonMessage.setSuccess("succeed");
		jsonMessage.setMessage("新增菜单成功");
		jsonMessage.setData(menu);
		return jsonMessage;
	}

	@RequestMapping({ "delete" })
	@ResponseBody
	public JsonMessage addMenuSubmit(int id) {
		try {
			this.wechatMenuDao.deleteById(id);
			return JsonMessage.getSuccessJson("删除菜单成功");
		} catch (Exception e) {
			return JsonMessage.getErrorJson("新增菜单失败:" + e.getMessage());
		}
	}

	@RequestMapping("old/config")
	public String config() {
		return "menu/wechat_menu_page";
	}

	@RequestMapping("old/createWeChatMenu")
	@ResponseBody
	public JsonMessage createWeChatMenu(@RequestParam String jsonMenu,
			HttpServletResponse response, HttpServletRequest request) {
		try {
			jsonMenu = jsonMenu.trim();
			String access_token = wechatConfigDao.getWechatToken()
					.getAccess_token();
			if (access_token != null) {
				if (StringUtils.isNotEmpty(access_token)) {
					String deleteResult = HttpClientUtil
							.get(Constant.DELETE_MENU + access_token);
					logger.info("菜单删除成功：" + deleteResult);
					JSONObject deleteObject = JSONObject
							.parseObject(deleteResult);
					if (deleteObject.getInteger("errcode") == 0) {
						String menuUrl = Constant.WX_MENU + access_token;
						String result = HttpUtil.getInstance().phpPost(menuUrl,
								JSONObject.parseObject(jsonMenu));
						if (StringUtils.isNotEmpty(result)) {
							JSONObject meunResult = JSONObject
									.parseObject(result);
							int code = meunResult.getInteger("errcode");
							if (code == 0) {
								WechatMenu wechatMenu = new WechatMenu();
								wechatMenu.setJson(jsonMenu);
								wechatMenu.setType(Constant.WECHATNAME);
								wechatMenuDao.updateWechatMenu(wechatMenu);
								logger.info("生成菜单成功");
								return JsonMessage.getSuccessJson("生成菜单成功");
							} else {
								logger.error("生成菜单失败");
								return JsonMessage.getErrorJson("生成菜单失败");
							}
						} else {
							logger.error("微信接口失败");
							return JsonMessage.getErrorJson("微信接口失败");
						}
					} else {
						logger.error("微信菜单删除失败");
						return JsonMessage.getErrorJson("微信菜单删除失败");
					}
				} else {
					logger.error("获取token失败");
					return JsonMessage.getErrorJson("获取token失败");
				}
			}
		} catch (Exception e) {
			logger.error("生成菜单失败", e);
			return JsonMessage.getErrorJson("生成菜单失败");
		}
		return JsonMessage.getErrorJson("生成菜单失败");
	}

}
